package cn.bankAutoOffice.realm;

import cn.bankAutoOffice.bean.entity.Employee;
import cn.bankAutoOffice.service.EmployeeService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author 金健伟
 * @DATE 2023/4/5 11:12
 * 功能说明：
 */

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private EmployeeService employeeService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户输入的账户
        String username = (String) authenticationToken.getPrincipal();
        System.out.println("****************"+authenticationToken.getPrincipal());
        // 通过username从数据库中查找 UserInfo 对象
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        Employee employee = employeeService.queryByName(Integer.parseInt(username));
        if (null == employee) {
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                employee, // 用户名
                employee.getEmpPassword(), // 密码
                ByteSource.Util.bytes(employee.getSalt()), // salt=username+salt
                getName() // realm name
        );
        return simpleAuthenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 能进入这里说明用户已经通过验证了
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        employeeService.getDepartment(employee.getDepartmentId()).forEach(
                empDepartment -> {
                    simpleAuthorizationInfo.addRole(empDepartment.getDepartmentName());
                    employeeService.getPermission(empDepartment.getId()).forEach(
                            empPermission -> {
                                simpleAuthorizationInfo.addStringPermission(empPermission.getPermission());
                            }
                    );
                }
        );
        return simpleAuthorizationInfo;
    }
}
